﻿using System.Windows.Forms;
using Finance.Properties;
using Finance.ViewModels;

namespace Finance.Views
{
	internal partial class DocumentBaseControl : UserControl
	{
		public DocumentBaseControl()
		{
			InitializeComponent();

			_contractorLabel.Text = Resources.DocumentBaseControl_ContractorLabel;
			_dateLabel.Text = Resources.DocumentBaseControl_DateLabel;
			_amountLabel.Text = Resources.DocumentBaseControl_AmountLabel;
			_typeLabel.Text = Resources.DocumentBaseControl_TypeLabel;

			_comboBoxContractor.DataSource = new BindingSource();
		}

		private DocumentViewModelBase _viewModel;

		public DocumentViewModelBase ViewModel
		{
			set
			{
				if (value == null)
					return;

				if (value == _viewModel)
					return;

				_viewModel = value;

				//Amount
				var amountBinding = new Binding("Text", _viewModel, "Amount", true, DataSourceUpdateMode.OnValidation);
				_textBoxAmount.DataBindings.Add(amountBinding);

                // SubType
				var typeBinding = new Binding("Text", _viewModel, "SubTypeName", true, DataSourceUpdateMode.OnValidation);
				_comboBoxSubType.DataBindings.Add(typeBinding);
				
				_comboBoxSubType.Items.Clear();
				foreach (string type in _viewModel.DocumentSubTypes)
				{
					_comboBoxSubType.Items.Add(type);
				}

				// Document Date
				var dateBinding = new Binding("Value", _viewModel, "DocDate", true, DataSourceUpdateMode.OnValidation);
				_dateTimePicker.DataBindings.Add(dateBinding);

				//Contractor
				var contractorsBinding = (BindingSource)_comboBoxContractor.DataSource;
				contractorsBinding.DataSource = _viewModel.Contractors;
				var contractorNameBinding = new Binding("Text", _viewModel, "ContractorName", true, DataSourceUpdateMode.OnValidation);
				_comboBoxContractor.DataBindings.Add(contractorNameBinding);
				var contractorBinding = new Binding("SelectedItem", _viewModel, "Contractor", true);
				_comboBoxContractor.DataBindings.Add(contractorBinding);
			}
		}

		public bool Apply()
		{
			//Validate
			if (string.IsNullOrEmpty(_comboBoxSubType.Text))
			{
				MessageBox.Show(Resources.DocumentControl_Apply_EnterType);
				return false;
			}

			if (!_viewModel.IsAmountValid)
			{
				MessageBox.Show(Resources.DocumentControl_Apply_InvalidAmount);
				return false;
			}
			_viewModel.ApplyChangesToModel();

			return true;
		}
	}
}
